/*
 * handle_read.c
 *
 *  Created on: 2009-5-5
 *      Author: tian
 */

#include"tcpipsim.h"

void handle_read(msg *pmsg){
	    msg retmsg;
		memset(&retmsg,0,sizeof(msg));
		//int i=0;
		struct tcpcb *ptcpcb=get_tcpcb_by_sock(pmsg->pid,pmsg->sock);
		if(ptcpcb==NULL){
			retmsg.mtype=pmsg->sock;
			retmsg.buflen=-1;
			if(msgsnd(pmsg->msgqid,&retmsg,sizeof(sockmsg)-sizeof(long),IPC_NOWAIT)<0){
				fprintf(stderr,"can not send message to application layer\n");
				return;
			}
		}
		else{
			retmsg.mtype=pmsg->sock;
			if(ptcpcb->recbeg==ptcpcb->recend&&ptcpcb->tcp_state!=TCP_ESTABLISHED){
				if(ptcpcb->getfin==0)
					retmsg.buflen=-2;
				else
					retmsg.buflen=0;
			}
			else if(ptcpcb->recbeg==ptcpcb->recend){
				retmsg.buflen=-2;
			}
			else{
				int i;
				int len=ptcpcb->recend-ptcpcb->recbeg;
				if(len<0)
					len+=BUFLEN*2;
				for(i=0;i<pmsg->buflen&&i<len;i++){
					retmsg.buf[i]=ptcpcb->recbuf[(ptcpcb->recbeg+i)%(2*BUFLEN)];
				}
				retmsg.buflen=i;
				ptcpcb->recbeg+=i;
				ptcpcb->recbeg%=(2*BUFLEN);
			}
			if(msgsnd(ptcpcb->msgqid,&retmsg,sizeof(sockmsg)-sizeof(long),IPC_NOWAIT)<0){
				fprintf(stderr,"can not send message to application layer\n");
				return;
			}
		}
}
